package com.pmcc.core.service;

import com.pmcc.core.entity.security.Region;
import com.pmcc.core.repository.RegionRepository;
import com.pmcc.core.vo.RegionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lihaiyue on 2018/3/28.
 */
@Service
@Transactional
public class RegionService {

    @Autowired
    RegionRepository regionRepository;

    /**
     * 异步查询区域树
     *
     * @return
     */
    @Transactional(readOnly = true)
    public List<RegionVo> queryRegionTree(Region region) {
        List<RegionVo> list = this.getChildren(region);
        if (list != null && list.size() > 0) {
            for (RegionVo regionVo : list) {
                List<RegionVo> childrenList = this.getChildren(regionVo);
                if (childrenList.size() > 0) {
                    regionVo.setChildren(new ArrayList<>());
                }
            }
        }
        return list;
    }

    /**
     * 传入实体，获取list子节点 vo
     *
     * @param region
     * @return
     */

    public List<RegionVo> getChildren(Region region) {
        List<RegionVo> children = new ArrayList<>();
        List<Region> childrenRegion = regionRepository.findByParentIdOrderByCode(region.getId());
        if (childrenRegion.size() > 0) {
            for (Region obj : childrenRegion) {
                children.add(RegionVo.getRegionVo(obj));
            }
        }
        return children;
    }

}
